package com.pzl.view;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

/**
 * 判断View是否在屏幕范围内
 */

public class ScreenView extends View {

    public ScreenView(Context context) {
        super(context);
    }

    public ScreenView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public boolean isViewInScreen() {
        int screenWidth = getScreenWidth(getContext());
        int screenHeight = getScreenHeight(getContext());
        Rect rect = new Rect(0, 0, screenWidth, screenHeight);
        int[] location = new int[2];
        getLocationInWindow(location);
        return getLocalVisibleRect(rect);
    }

    /**
     * 获得屏幕的宽度
     *
     * @param context context
     * @return width
     */
    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    /**
     * 获得屏幕的高度
     *
     * @param context context
     * @return height
     */
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

}
